#!/usr/bin/python3

import urllib.request
import json
import simplejson
import sys

corpid = 'ww5137e2461c732e92'  # CorpID是企业号的标识
agent_id = "1000003"    # 企业号中的应用id
corpsecret = 'xxxxx'  # 应用的Secret


def gettoken(corp_id, corp_secret):
    gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corp_id + '&corpsecret=' + corp_secret
    print(gettoken_url)
    try:
        token_file = urllib.request.urlopen(gettoken_url)
    except urllib.request.HTTPError as e:
        print(e.code)
        print(e.read().decode("utf8"))
        sys.exit()
    token_data = token_file.read().decode('utf-8')
    token_json = json.loads(token_data)
    token_json.keys()
    token = token_json['access_token']
    return token


def senddata(access_token, user_id, department_id, title, message):
    send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token
    send_values = {
        "touser": user_id,       # 企业号中的用户帐号，在zabbix用户Media中配置，如果配置不正常，将按部门发送
        "toparty": department_id,
        "msgtype": "textcard",
        "agentid": agent_id,
        "textcard": {
            "title": title,
            "description": message,
            "url": "http://zabbix.xiodi.cn/index.php",
            "btntxt": "详细"
        },
        "safe": "0"
    }
    send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8')
    #print(send_data)
    send_request = urllib.request.Request(send_url,send_data)
    #print(send_request)
    response = json.loads(urllib.request.urlopen(send_request).read())
    print(str(response))


if __name__ == '__main__':
    user = sys.argv[1]
    department = sys.argv[2]
    subject = sys.argv[3]
    content = sys.argv[4]

    accesstoken = gettoken(corpid, corpsecret)
    senddata(accesstoken, user, department, subject, content)
